import { getStorageSync, request } from '@tarojs/taro';
import { toast } from '@/common/utils/toast';
import config, { baseUrl } from './request.config';

class TaroRequest {
  static token: string = '';
  static taroRequest<T>(method = 'POST' as 'POST' | 'GET' | 'PUT' | 'DELETE') {
    return (
      requestUrl: string,
      data = {},
      needToken: boolean = true
    ): Promise<T> => {
      return new Promise((resolve, reject) => {
        let errFlag = false;
        const url = ~requestUrl.indexOf('http')
          ? requestUrl
          : baseUrl.concat(requestUrl);
        request({
          url,
          data,
          method,
          success: (res) => {
            if (res.statusCode === 200 && res.data.code === 200) {
              resolve(res.data);
              return res.data;
            }
            errFlag = true;
            reject(res.data.msg);
          },
          fail: () => {
            errFlag = true;
          },
          complete: (res: any) => {
            // isShowLoading && hideLoading()
            if (errFlag) {
              const code =
                res.statusCode !== 200 ? res.statusCode : res.data.code;
              switch (code) {
                case 401:
                case 403:
                  // 进入login 是tab页主要是首页不会弹出登录弹窗  主动点击登录 可以返回  可以在页面点登录
                  // 非tab页 是清除返回  非login页登录
                  // router('login');
                  //   navigateTo({ url: '/pages/login/index?type=login' });
                  toast('登录过期，请重新登录');
                  return;
                default:
                  toast(res?.data?.msg || '网络开小差了');
                  return;
              }
            }
          },
          ...config,
          header: {
            ...config.header,
            ...this.getToken(needToken),
            ...JSON.parse(
              JSON.stringify({
                userCode: getStorageSync('userCode').userCode,
                promoterId: getStorageSync('promoterId').promoterId,
              })
            ),
          },
        });
      });
    };
  }
  static getToken(needToken: boolean) {
    const header: { Authorization: string | undefined } = {
      Authorization: '',
    };
    // const storageToken = getStorageSync('token');
    // const token = storageToken;
    header.Authorization = this.token;
    if (!needToken) {
      delete header.Authorization;
      return header;
    }
    return header;
  }
  // 兼容微信登录不能传token问题  needToken
  post<T>(url: string, data = {}, needToken: boolean = true) {
    return TaroRequest.taroRequest<resInterface<dataType<T>>>()(
      url,
      data,
      needToken
    );
  }
  get<T>(url: string, data = {}) {
    return TaroRequest.taroRequest<resInterface<dataType<T>>>('GET')(url, data);
  }
  put<T>(url: string, data = {}) {
    return TaroRequest.taroRequest<resInterface<dataType<T>>>('PUT')(url, data);
  }
  delete<T>(url: string, data = {}) {
    return TaroRequest.taroRequest<resInterface<dataType<T>>>('DELETE')(
      url,
      data
    );
  }
}

export const post = new TaroRequest().post;
export const get = new TaroRequest().get;
export const put = new TaroRequest().put;
export const del = new TaroRequest().delete;

export default TaroRequest;

type dataType<T> = T extends infer R ? R : never;
